/*
 * Copyright (c) China Telecom Cloud Technology Co., Ltd. 2024-2025. All rights reserved.
 */
#ifndef SAFEQUEUE_H
#define SAFEQUEUE_H

#include <mutex>
#include <queue>


//! 线程安全的队列(用于存放待处理的任务)
template <typename T>
class SafeQueue {
private:
    std::queue<T> _queue;
    std::mutex    _mutex;

public:
    SafeQueue() {}
    SafeQueue(SafeQueue &other) {}

    ~SafeQueue() {}

    bool empty() {
        //! RAII风格
        std::unique_lock<std::mutex> lock_guard(_mutex);
        return _queue.empty();
    }

    int size() {
        std::unique_lock<std::mutex> lock_guard(_mutex);
        return _queue.size();
    }

    /**
     *! @brief 元素入队操作
     * 
     * @param t 
     */
    void enqueue(T &val) {
        std::unique_lock<std::mutex> lock_guard(_mutex);
        _queue.push(val);
    }

    /**
     *! @brief 元素出队
     * 
     * @param val 
     */
    bool dequeue(T &val)
    {
        std::unique_lock<std::mutex> lock_guard(_mutex);

        if (_queue.empty()) {
            return false;
        }
        val = std::move(_queue.front());

        _queue.pop();
        return true;
    }
};

#endif